package main

import (
	"database/sql"
	"fmt"
	"github.com/yourusername/gox/pkg/runtime"
	"strings"
	"time"
)

type User struct {
	ID        int
	Name      string
	Email     string
	Status    string
	CreatedAt time.Time
}

// 示例1: 使用 {} 进行文本插入（表名、字段名、SQL片段）
func GetDataFromTable(db *sql.DB, tableName string, orderBy string) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_4_builder := runtime.NewQueryBuilder()
		__gox_sql_4_builder.AddText("SELECT id, name, email, status, created_at FROM")
		__gox_sql_4_builder.AddText(fmt.Sprintf("%v", tableName))
		__gox_sql_4_builder.AddText("ORDER BY")
		__gox_sql_4_builder.AddText(fmt.Sprintf("%v", orderBy))
		__gox_sql_4 := __gox_sql_4_builder.Build()
		return __gox_sql_4
	}()

	rows, err := db.Query(query.String(), query.Args()...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

// 示例2: 使用 #{} 进行参数化查询（防SQL注入）
func GetUsersByStatus(db *sql.DB, status string, minAge int) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_3_builder := runtime.NewQueryBuilder()
		__gox_sql_3_builder.AddText("SELECT id, name, email, status, created_at FROM users WHERE status =")
		__gox_sql_3_builder.AddParam(status)
		__gox_sql_3_builder.AddText("AND age >=")
		__gox_sql_3_builder.AddParam(minAge)
		__gox_sql_3 := __gox_sql_3_builder.Build()
		return __gox_sql_3
	}()

	rows, err := db.Query(query.String(), query.Args()...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

// 示例3: 混合使用两种语法
func SearchUsersAdvanced(db *sql.DB, tableName string, keyword string, statusFilter bool, activeStatus string) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_2_builder := runtime.NewQueryBuilder()
		__gox_sql_2_builder.AddText("SELECT id, name, email, status, created_at FROM")
		__gox_sql_2_builder.AddText(fmt.Sprintf("%v", tableName))
		__gox_sql_2_builder.AddText("WHERE (name LIKE")
		__gox_sql_2_builder.AddParam("%" + keyword + "%")
		__gox_sql_2_builder.AddText("OR email LIKE")
		__gox_sql_2_builder.AddParam("%" + keyword + "%")
		__gox_sql_2_builder.AddText(")")
		__gox_sql_2_builder.AddText(fmt.Sprintf("%v", func() interface{} {
			if statusFilter {
				return "AND status = ?"
			}
			return ""
		}()))
		__gox_sql_2_builder.AddText("ORDER BY created_at DESC")
		__gox_sql_2 := __gox_sql_2_builder.Build()
		return __gox_sql_2
	}()

	var args []interface{}
	args = append(args, query.Args()...)
	if statusFilter {
		args = append(args, activeStatus)
	}

	rows, err := db.Query(query.String(), args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

// 示例4: 复杂代码块处理
func BuildDynamicQuery(db *sql.DB, conditions map[string]interface{}) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_1_builder := runtime.NewQueryBuilder()
		__gox_sql_1_builder.AddText("SELECT id, name, email, status, created_at FROM users WHERE 1=1")
		__gox_sql_1_builder.AddText(fmt.Sprintf("%v", func() interface{} {
			var parts []string
			for field := range conditions {
				switch field {
				case "name":
					parts = append(parts, "AND name LIKE ?")
				case "email":
					parts = append(parts, "AND email = ?")
				case "status":
					parts = append(parts, "AND status = ?")
				case "age_min":
					parts = append(parts, "AND age >= ?")
				}
			}
			return strings.Join(parts, " ")
		}()))
		__gox_sql_1_builder.AddText("ORDER BY created_at DESC")
		__gox_sql_1 := __gox_sql_1_builder.Build()
		return __gox_sql_1
	}()

	var args []interface{}
	for field, value := range conditions {
		switch field {
		case "name", "email", "status", "age_min":
			args = append(args, value)
		}
	}

	rows, err := db.Query(query.String(), args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

// 示例5: 条件逻辑处理（现在可以在大括号内使用了！）
func GetUsersWithComplexFilter(db *sql.DB, userID int, includeInactive bool) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_0_builder := runtime.NewQueryBuilder()
		__gox_sql_0_builder.AddText("SELECT id, name, email, status, created_at FROM users WHERE id =")
		__gox_sql_0_builder.AddParam(userID)
		__gox_sql_0_builder.AddText(fmt.Sprintf("%v", func() interface{} {
			if includeInactive {
				return ""
			} else {
				return "AND status = 'active'"
			}
		}()))
		__gox_sql_0_builder.AddText("AND deleted_at IS NULL ORDER BY created_at DESC")
		__gox_sql_0 := __gox_sql_0_builder.Build()
		return __gox_sql_0
	}()

	rows, err := db.Query(query.String(), query.Args()...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

func main() {
	fmt.Println("GoX 新语法示例程序")
	fmt.Println("- {expression}  : 文本插入")
	fmt.Println("- #{expression} : 参数化查询")
	fmt.Println("- 支持复杂代码块和条件逻辑")
}
